package bean

import (
	"log"
	"strings"

	"user-agent/database"
	"user-agent/database/schema"

	"github.com/huyinghuan/moment"
)

type StatisticsBean struct{}

func (bean *StatisticsBean) GetList(id string, start int64, end int64) ([]schema.Statistics, error) {
	engine := database.GetDriver()
	list := []schema.Statistics{}
	query := []interface{}{
		id,
	}
	queue := []string{
		"mac = ?",
	}
	if start != 0 {
		query = append(query, start)
		queue = append(queue, "created_time >= ?")
	}
	if end != 0 {
		query = append(query, end)
		queue = append(queue, "created_time <= ?")
	}
	err := engine.SQL("select * from statistics where "+strings.Join(queue, " and "), query...).Find(&list)
	return list, err
}

func (bean *StatisticsBean) GetAll(id string) ([]schema.Statistics, error) {
	engine := database.GetDriver()
	list := []schema.Statistics{}
	err := engine.SQL("select * from statistics where mac = ?", id).Find(&list)
	return list, err
}

func (bean *StatisticsBean) InertOrUpdate(id string, syncTime int64) (int64, error) {
	syncDate := moment.NewFromUnix(syncTime)
	start, end := syncDate.Today()
	aliveBean := &AliveBean{}
	count, err := aliveBean.GetPeriodCount(id, start.Unix(), end.Unix())
	if err != nil {
		return count, err
	}
	item := &schema.Statistics{
		Mac:         id,
		CreatedTime: start.Unix(),
		Count:       count,
		CreatedDate: syncDate.Format("YYYY-MM-DD"),
	}

	engine := database.GetDriver()
	queryItem := &schema.Statistics{
		Mac:         item.Mac,
		CreatedDate: item.CreatedDate,
	}
	has, err := engine.Get(queryItem)
	if err != nil {
		return count, err
	}
	//存在就更新数据
	if has {
		queryItem.Count = count
		log.Println(queryItem)
		if _, err := engine.ID(queryItem.ID).Update(queryItem); err != nil {
			return count, err
		}
		return count, nil
	}
	_, err = engine.Insert(item)
	return count, err
}
